import React, {useCallback, useEffect, useState} from "react"
import {Button, Col, DatePicker, Form, Row, Select, Space, Table, TimePicker} from "antd";
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import FormDrawer from "../../components/FormDrawer";
import DataPageLayout from "../../components/DataPageLayout";
import AuthorizationResource from "../../components/AuthorizationResource";
import {NumberIdAndName} from "../../types/BasicModels";
import {
    AddProcurementRequest,
    createProcurement, deleteProcurement,
    getAllProcurementCreatedEmployees, ProcurementStatus, procurementStatuses, procurementStatusMap,
    QueryProcurementResponse,
    queryProcurements
} from "../../apis/ProcurementApi";
import {useNavigate, useSearchParams} from "react-router-dom";
import {Pageable} from "../../utils/Page";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {Link} from "react-router-dom";
import {createProcurementSupplier, getAllProcurementSupplier} from "../../apis/ProcurementSupplierApi";
import {useGlobalStyle} from "../../global.style";
import {FormInstance} from "antd/es/form/hooks/useForm";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";
import QuickCreatableSelectFormItem from "../QuickCreatableSelectFormItem";
import {LocalDate, LocalDateTime, LocalTime, OffsetDateTime, ZoneOffset} from "@js-joda/core";
import {Dayjs} from "dayjs";
import LoadableButton from "../LoadableButton";
import {deleteMarketOrder} from "../../apis/MarketOrderApi";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";

export interface pageProps {

}

export interface ProcurementFormData {
    supplierId: number
    createdTime: Dayjs
    createdDate: Dayjs
}


const ProcurementPage: React.FC<pageProps> = (props) => {

    let globalStyle = useGlobalStyle();
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryProcurementResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [supplierIds, setMarketIds] = useState<number[]>(urlSearchParams.getAll("supplierIds").map(it => parseInt(it)))
    const [createdByIds, setCreatedByIds] = useState<number[]>([])


    const [procurementSuppliers, setProcurementSuppliers] = useState<Array<NumberIdAndName>>([])

    function queryAllProcurementSupplier() {
        return getAllProcurementSupplier().then(response => {
            setProcurementSuppliers(response.data)
        })
    }

    useEffect(() => {

        queryAllProcurementSupplier();
    }, []);

    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startDate, setStartDate] = useState<LocalDate>()
    const [endDate, setEndDate] = useState<LocalDate>()
    const [status, setStatus] = useState<ProcurementStatus>()
    const query = useCallback(() => {
        setLoading(true)
        queryProcurements({
            supplierIds,
            createdByIds,
            startDate: startDate ? startDate.toJSON() : undefined,
            endDate: endDate ? endDate.toJSON() : undefined,
            status,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), supplierIds, createdByIds, startDate, endDate, status])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllProcurementCreatedEmployees().then(response => response.data).then(setCreatedByEmployees)
    }, []);
    let [addForm] = Form.useForm();

    // let [updateFrom] = Form.useForm();
    function buildFormItems(formInstance: FormInstance) {
        return <>
            <QuickCreatableSelectFormItem name={"supplierId"} label={"供货商"}
                                          required={true}
                                          onRefresh={queryAllProcurementSupplier}
                                          options={procurementSuppliers.map(it => ({label: it.name, value: it.id,}))}
                                          onCreate={async (name) => {
                                              let id = (await createProcurementSupplier({name})).data;
                                              procurementSuppliers.push({id, name})
                                              setProcurementSuppliers(Array.from(procurementSuppliers))
                                              formInstance.setFieldValue("supplierId", id)
                                          }}/>
            <Form.Item name={"createdDate"} label={"下单日期"}>
                <DatePicker mode={"date"}></DatePicker>
            </Form.Item>
            <Form.Item name={"createdTime"} label={"下单时间"}>
                <TimePicker></TimePicker>
            </Form.Item>
        </>
    }

    let navigate = useNavigate();
    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["采购_入库_入库"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>开单</Button>
        </AuthorizationResource>}>
            <Table<QueryProcurementResponse> className={globalStyle.rowClickableTable} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/procurements/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setMarketIds(filters["supplier.name"] as number[])
                setCreatedByIds(filters["createdBy.name"] as number[])
                let filter = filters["status"] as unknown as ProcurementStatus[];
                setStatus(filter ? filter[0] : undefined)
            }}>
                <Table.Column<QueryProcurementResponse> filteredValue={supplierIds} dataIndex={["supplier", "name"]}
                                                        title={"供货商"}
                                                        filters={procurementSuppliers.map(supplier => {
                                                            return {
                                                                text: supplier.name,
                                                                value: supplier.id,
                                                            }
                                                        })} render={(_, record) => {
                    return record.supplier.name
                }}/>
                <Table.Column dataIndex={"createdDateTime"} title={"下单时间"}
                              {...useTableFilterDateRangeColumnProps<QueryProcurementResponse>("createdDateTime", {
                                  handleSearch: value => {
                                      setStartDate(value ? OffsetDateTime.parse(value[0].format()).toLocalDate() : undefined)
                                      setEndDate(value ? OffsetDateTime.parse(value[1].format()).toLocalDate() : undefined)
                                  }
                              })}
                              render={(value) => value.format(DATE_WITH_TIME_FORMATER)}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                <Table.Column title={"费用"} dataIndex={"totalFee"}/>
                <Table.Column<QueryProcurementResponse> dataIndex={"status"}
                                                        filteredValue={status ? [status] : []}
                                                        title={"状态"}
                                                        key={"status"}
                                                        filterMultiple={false}
                                                        filters={procurementStatuses.map(it => ({
                                                            text: procurementStatusMap[it],
                                                            value: it
                                                        }))} render={(value, record) => {
                    return value === "RECEIPT" ? <Link onClick={event => {
                        event.stopPropagation()
                    }}
                                                       to={`/procurements/receipts/${record.receiptId}`}>已入库</Link> : procurementStatusMap[value]
                }}/>
                <Table.Column dataIndex={"note"} title={"备注"}/>
                <Table.Column dataIndex={["createdBy", "name"]} title={"下单人员"}
                              filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
                <Table.Column<QueryProcurementResponse> title={"操作"} dataIndex={"action"} render={(_, record) => {
                    return <>
                        {employeeAuthorizationStore.hasAuthority("采购_删除") && record.status === "WAIT_SUBMIT" &&
                            <LoadableButton danger type={"text"} onClick={async (event) => {
                                event.stopPropagation()
                                await deleteProcurement(record.id)
                                query()
                            }}><DeleteOutlined/>删除</LoadableButton>}
                    </>
                }}>

                </Table.Column>
            </Table>
        </DataPageLayout>
        <FormDrawer<ProcurementFormData> form={addForm} onClose={() => setOpenAddDrawer(false)}
                                         title={"下单"}
                                         onConfirm={async (values) => {
                                             const request: AddProcurementRequest = {}
                                             const createdDate = values.createdDate
                                             if (createdDate != null) {

                                                 let localDateTime = LocalDateTime.of(LocalDate.of(createdDate.year(), createdDate.month() + 1, createdDate.date()), !!values.createdTime ? LocalTime.of(values.createdTime.hour(), values.createdTime.minute(), values.createdTime.second()) : LocalTime.now());
                                                 request.createdDateTime = OffsetDateTime.of(localDateTime,OffsetDateTime.now().offset())
                                             }
                                             return createProcurement(values.supplierId, request).then(response => {
                                                 setOpenAddDrawer(false)
                                                 navigate(`/procurements/${response.data}`)
                                                 query()
                                             })
                                         }}
                                         open={openAddDrawer}>
            {buildFormItems(addForm)}
        </FormDrawer>
    </>
}
export default observerDashboardPageWrapper(ProcurementPage, "procurements", "采购")
